package com.sun.controller;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
public class QQLoginController {

    @Value("${qq.appId}")
    private String appId;

    @Value("${qq.redirectUri}")
    private String redirectUri;

    private final CloseableHttpClient httpClient = HttpClients.createDefault();

    @GetMapping("/auth/qq/login")
    public void qqLogin(HttpServletResponse response, HttpSession session) throws IOException {
        String state = "STATE";
        session.setAttribute("qq_oauth_state", state);

        String url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id="
                + appId + "&redirect_uri=" + redirectUri + "&state=" + state;

        response.sendRedirect(url);
    }

    @GetMapping("/auth/qq/callback")
    public String qqCallback(@RequestParam String code, @RequestParam String state, HttpSession session) throws IOException {
        String storedState = (String) session.getAttribute("qq_oauth_state");
        if (storedState == null || !storedState.equals(state)) {
            return "Error: state does not match";
        }

        try {
            String accessToken = getAccessToken(code);
            String openId = getOpenId(accessToken);
            String userInfo = getUserInfo(accessToken, openId);

            // 这里可以进行用户注册或登录操作
            // 返回登录用户的信息
            return "redirect:/home";
        } catch (IOException e) {
            return "Error occurred during QQ auth: " + e.getMessage();
        }
    }

    private String getAccessToken(String code) throws IOException {
        String url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id="
                + appId + "&client_secret=" + appId + "&code=" + code + "&redirect_uri=" + redirectUri;

        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        String responseStr = EntityUtils.toString(response.getEntity());
        String accessToken = responseStr.split("&")[0].split("=")[1];
        return accessToken;
    }

    private String getOpenId(String accessToken) throws IOException {
        String url = "https://graph.qq.com/oauth2.0/me?access_token=" + accessToken;

        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        String responseStr = EntityUtils.toString(response.getEntity());
        String openId = responseStr.substring(responseStr.lastIndexOf(":\"") + 2, responseStr.lastIndexOf("\"}"));
        return openId;
    }

    private String getUserInfo(String accessToken, String openId) throws IOException {
        String url = "https://graph.qq.com/user/get_user_info?access_token=" + accessToken + "&oauth_consumer_key="
                + appId + "&openid=" + openId;

        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        String responseStr = EntityUtils.toString(response.getEntity());
        return responseStr;
    }
}